package logic

import (
	"context"
	"encoding/json"
	"housing/models/cache"
	"housing/models/mysql"
	"time"

	"housing/houserpc/houserpc"
	"housing/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SeekListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSeekListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SeekListLogic {
	return &SeekListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SeekListLogic) SeekList(in *houserpc.SeekListRequest) (*houserpc.SeekListResponse, error) {
	// todo: add your logic here and delete this line

	var seek []mysql.Seek
	result, _ := cache.Rdb.Get(l.ctx, "seekList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&seek)
		marshal, _ := json.Marshal(seek)
		cache.Rdb.Set(l.ctx, "seekList", marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &seek)
	}

	var seekList []*houserpc.SeekList
	for _, m := range seek {
		list := houserpc.SeekList{
			SeekId:  int64(m.ID),
			UserId:  m.UserId,
			HouseId: m.HouseId,
			Comment: m.Comment,
		}
		seekList = append(seekList, &list)
	}
	return &houserpc.SeekListResponse{
		List: seekList,
	}, nil
}
